from rest_framework import serializers
from .models import Order, OrderItem
from products.serializers import ProductSerializer

class OrderItemSerializer(serializers.ModelSerializer):
    product = ProductSerializer(read_only=True)
    product_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = OrderItem
        fields = ['id', 'order', 'product', 'product_id', 'quantity', 'price']
        read_only_fields = ['price']

class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)
    customer_name = serializers.CharField(source='customer.username', read_only=True)

    class Meta:
        model = Order
        fields = ['id', 'customer', 'customer_name', 'status', 'total_amount', 
                 'created_at', 'updated_at', 'items']
        read_only_fields = ['total_amount', 'created_at', 'updated_at']

    def create(self, validated_data):
        items_data = self.context.get('items', [])
        order = Order.objects.create(**validated_data)
        
        total_amount = 0
        for item_data in items_data:
            item_data['order'] = order
            item = OrderItem.objects.create(**item_data)
            total_amount += item.price * item.quantity
            
        order.total_amount = total_amount
        order.save()
        
        return order 